﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tuwien.auto.eibclient;
using KNXFramework.Logging;

namespace KNXFramework.KNXObjects.ValueObjects
{
    internal class ValueObject32Value : IValueObject
    {
        private double m_Value;

        #region Constructors
        public ValueObject32Value(string value)
        {
            if (!double.TryParse(value, out m_Value))
                throw new ApplicationException("ValueObject32Value: cannot parse input value to double. Val : " + value);
        }
        public ValueObject32Value(EIBBuffer buffer)
        {
            if (buffer.data.Length < 6)
            {
                CustomLogger.WriteErrorEntry("Invalid packet received for ValueObject32 (too short)");
                return;
            }
            m_Value = Convert.ToDouble(buffer.data[2]<<24 | buffer.data[3]<<16 | buffer.data[4]<<8 | buffer.data[5]);
        }
        #endregion

        public override string ToString()
        {
            return m_Value.ToString("#.########");
        }

        #region IValueObject Members

        public void AdaptBufferBeforeSending(bool isWrite, tuwien.auto.eibclient.EIBBuffer buffer)
        {
            byte[] b = new byte[6];
            b[0] = 0;
            b[1] = buffer.data[1];
            UInt32 temp = Convert.ToUInt32(m_Value);
            buffer.data[5] = (byte)(temp & 0x000000FF);
            buffer.data[4] = (byte)((temp & 0x0000FF00) >> 8);
            buffer.data[3] = (byte)((temp & 0x00FF0000) >> 16);
            buffer.data[2] = (byte)((temp & 0xFF000000) >> 24);
            buffer.data = b;
        }

        #endregion

        #region IEquatable<IValueObject> Members

        public bool Equals(IValueObject other)
        {
            ValueObject32Value otherVal = other as ValueObject32Value;
            bool equality = false;
            if (otherVal != null)
                equality = m_Value.Equals(otherVal.m_Value);
            return equality;
        }

        #endregion
    }
}
